package com.buka.recipe.system.service.impl;

import com.buka.recipe.system.entity.Role;
import com.buka.recipe.system.repository.RoleRepository;
import com.buka.recipe.system.service.RoleService;
import jakarta.persistence.criteria.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    private final RoleRepository roleRepository;

    @Autowired
    public RoleServiceImpl(RoleRepository roleRepository) {
        this.roleRepository = roleRepository;
    }

    @Override
    public List<Role> getRoleByIds(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return List.of();
        }
        return roleRepository.findAllById(ids);
    }

    @Override
    public Page<Role> getAll(String name, Integer current, Integer pageSize) {
        Sort sort = Sort.by(new Sort.Order(Sort.Direction.DESC, "id"));
        Pageable pageable = PageRequest.of(current, pageSize, sort);
        Specification<Role> specification = (root, query, builder) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.hasLength(name)) {
                list.add(builder.like(root.get("name"), "%" + name + "%"));
            }
            Predicate[] predicates = new Predicate[list.size()];
            return builder.and(list.toArray(predicates));
        };
        return roleRepository.findAll(specification, pageable);
    }
}
